<template>
  <div>
    <h2>test</h2>
    <h1>{{myRefData}}</h1>
    <input type="text" v-model="myRefData">
    <Grandson />
  </div>
</template>

<script>
import Grandson from "./Grandson.vue";
import { toRef, toRefs, ref, reactive, customRef } from "vue";
export default {
  name: "Son2",
  components: { Grandson },
  setup() {
    let person = reactive({
      name: "carlos",
      age: 25,
      job: {
        job1: { salary: 10 },
      },
    });
    function myRef(v, delay) {
      return customRef((track, trigger) => {
        let timer;
        return {
          get() {
            // console.log("有人调用了get", v);
            // 如果不写track()，那么vue只会监视setup上来时候调用get。写了就代表每一次get都会监视
            track();
            return v;
          },
          set(newV) {
            // 我们甚至还完成了防抖的功能！nicejob
            clearTimeout(timer);
            timer = setTimeout(() => {
              console.log("有人调用了set", newV);
              v = newV;
              // trigger代表我们手动调用了get()。前面这句话不对，其实是通知vue去重新解析视图层
              trigger();
            }, delay);
          },
        };
      });
    }
    let myRefData = myRef("abc", 1000);
    /* return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve({
          name: toRef(person, "name"),
          salary: toRef(person.job.job1, "salary"),
          ...toRefs(person),
          myRefData,
        });
      }, 1000);
    }); */
    return {
      name: toRef(person, "name"),
      salary: toRef(person.job.job1, "salary"),
      ...toRefs(person),
      myRefData,
    };
  },
};
</script>

<style>
</style>